#include "gpio.h"

#define gpio_path "/sys/class/gpio/export"
#define gpio1_path "/sys/class/gpio/gpio1/"
#define gpio2_path "/sys/class/gpio/gpio2/"

extern sem_t sem_gpio;
extern unsigned char direction;
/*
*   fd1_gpio -> GPIO_1
*   fd2_gpio -> GPIO_2
*   往前 0-180度    GPIO_1 = 1  GPIO_2 = 0
*   往后 180-360度  GPIO_1 = 0  GPIO_2 = 1
*/
void gpio_init(void)
{
    int fd1_gpio;
    int fd2_gpio;
    /*************************** GPIO_1 ***************************/
    fd1_gpio = open(gpio_path, O_WRONLY);
    if( fd1_gpio < 0 ){
        printf("gpio1 export file open error\n");
        exit(-1);
    }
    write(fd1_gpio, "1", 1);
    /***/
    fd1_gpio = open(gpio1_path"direction", O_WRONLY);
    if( fd1_gpio < 0 ){
        printf("gpio1 direction file open error\n");
        close(fd1_gpio);
        exit(-1);
    }
    write(fd1_gpio, "low", 3);
    /***/
    fd1_gpio = open(gpio1_path"value", O_WRONLY);
    if( fd1_gpio < 0 ){
        printf("gpio1 value file open error\n");
        close(fd1_gpio);
        exit(-1);
    }
    /**************************************************************/

    /*************************** GPIO_2 ***************************/
    fd2_gpio = open(gpio_path, O_WRONLY);
    if( fd2_gpio < 0 ){
        printf("gpio2 export file open error\n");
        close(fd1_gpio);
        exit(-1);
    }
    write(fd2_gpio, "2", 1);
    /***/
    fd2_gpio = open(gpio2_path"direction", O_WRONLY);
    if( fd2_gpio < 0 ){
        printf("gpio2 direction file open error\n");
        close(fd1_gpio);
        close(fd2_gpio);
        exit(-1);
    }
    write(fd2_gpio, "high", 4);
    /***/
    fd2_gpio = open(gpio2_path"value", O_WRONLY);
    if( fd2_gpio < 0 ){
        printf("gpio2 value file open error\n");
        close(fd1_gpio);
        close(fd2_gpio);
        exit(-1);
    }
    /**************************************************************/

    write(fd1_gpio, "0", 1);
    write(fd2_gpio, "1", 1);

    while (1)
    {
        // P操作 等待信号 -1
        sem_wait(&sem_gpio);
        if( direction == 0 ){
            write(fd1_gpio, "0", 1);
            write(fd2_gpio, "1", 1);
        }
        if( direction == 1 ){
            write(fd1_gpio, "1", 1);
            write(fd2_gpio, "0", 1);
        }
        sem_post(&sem_gpio);
        usleep(1*1000);
    }

    close(fd1_gpio);
    close(fd2_gpio);

    exit(0);
}
